package com.donggua.aichebao.login;

import android.app.Activity;
import android.app.Notification;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Button;


/**
 * Created by fzh on 17-9-5.
 */

public class DGCheckCodeTask extends Thread{
    private Handler mLoopHandler;
    private Handler mUiHandler;
    private final static int ALLTIME = 60;
    private int mTime = ALLTIME-1;
    private Button btnCheckCode;
    private final String mGetCodeStr;
    private final String mGetCheckCode;
    public DGCheckCodeTask(Context context,Button checkCodeBtn){
        btnCheckCode = checkCodeBtn;
        mGetCodeStr = context.getResources().getString(R.string.loginGetCode);
        mGetCheckCode = context.getResources().getString(R.string.loginGetCheckCode);
        setmUiHandler();
    }

    private void setmUiHandler(){
        mUiHandler = new Handler(){
            public void handleMessage(Message msg){
                super.handleMessage(msg);
                if(msg.what == 0){
                    btnCheckCode.setEnabled(true);
                    btnCheckCode.setText(mGetCheckCode);
                }else{
                    btnCheckCode.setText(mGetCodeStr+msg.what+"s");
                }

            }
        };
    }
    public void run(){
        super.run();
        Looper.prepare();
        mLoopHandler = new Handler() {
           public void handleMessage(Message msg){
               super.handleMessage(msg);
               mTime = msg.what;
               while (true){

                   try {
                       Thread.sleep(1000);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   mTime--;
                   mUiHandler.sendEmptyMessage(mTime);
                   if(mTime == 0){
                       break;
                   }
               }
           }
        };
        Looper.loop();
    }

    public void startTask(){
        start();
    }

    public void stopTask(){
        mLoopHandler.getLooper().quit();
    }

    public void statCountTime(){
        if(mLoopHandler != null){
            mLoopHandler.sendEmptyMessage(ALLTIME);
        }

    }
}
